package me.jiatao.taobaotools;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by JiaTao on 2018/8/1.
 * Email: 535318720@qq.com
 * Version: 1.0
 * Description:
 */
public class FileProvider extends ContentProvider {
    private static final String URI_PREFIX = "content://me.jiatao.taobaotools";

    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {

        File file = new File(uri.getPath());
        ParcelFileDescriptor parcel = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
        return parcel;
    }

    @Override
    public AssetFileDescriptor openAssetFile (Uri uri, String mode) throws FileNotFoundException{
        AssetManager am = getContext().getAssets();
        String path = uri.getPath().substring(1);
        Log.i("111111111111", "111111111111---->"+path);
        File file = new File(path);
        if (file.exists()) {
            Log.i("222222", "222222---->"+path);
            Uri turi = Uri.parse(URI_PREFIX+"/"+path);
            return super.openAssetFile(turi, mode);
        }
        try {
            AssetFileDescriptor afd = am.openFd(path);
            return afd;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return super.openAssetFile(uri, mode);
    }



    @Override
    public boolean onCreate() {
        return false;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        return null;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }
}
